<template>
	<div class="quill_editor_wrapper">
		<div class="editor" ref="editor" :style="styles"></div>
		<el-upload
			ref="upload"
			class="upload"
			:action="uploadUrl"
			:data="uploadParams"
			:accept="uploadAccept"
			:headers="uploadHeader"
			:on-success="handleUploadSuccess"
			:before-upload="handleBeforeUpload"
		>
			<el-button class="uploadBtn"></el-button>
		</el-upload>
	</div>
</template>

<script>
import Quill from 'quill';
import { mapGetters } from 'vuex';
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
//富文本图片拖动，调整大小插件
import ImageResize from 'quill-image-resize-module';
import { ImageDrop } from 'quill-image-drop-module';
import { ImageExtend } from 'quill-image-extend-module';
Quill.register('modules/imageExtend', ImageExtend);
Quill.register('modules/imageResize', ImageResize);
Quill.register('modules/imageDrop', ImageDrop);
const titleConfig = {
	'ql-bold': '加粗',
	'ql-color': '颜色',
	'ql-font': '字体',
	'ql-code': '插入代码',
	'ql-italic': '斜体',
	'ql-link': '添加链接',
	'ql-background': '颜色',
	'ql-size': '字体大小',
	'ql-strike': '删除线',
	'ql-script': '上标/下标',
	'ql-underline': '下划线',
	'ql-blockquote': '引用',
	'ql-header': '标题',
	'ql-indent': '缩进',
	'ql-list': '列表',
	'ql-align': '文本对齐',
	'ql-direction': '文本方向',
	'ql-code-block': '代码块',
	'ql-formula': '公式',
	'ql-image': '图片',
	'ql-video': '视频',
	'ql-clean': '清除字体样式',
	'ql-upload': '文件',
	'ql-table': '插入表格',
	'ql-table-insert-row': '插入行',
	'ql-table-insert-column': '插入列',
	'ql-table-delete-row': '删除行',
	'ql-table-delete-column': '删除列'
};
export default {
	name: 'quillEditor',
	props: {
		/* 编辑器的内容 */
		value: { type: String, default: '' },
		/* 高度 */
		height: { type: Number, default: 320 },
		/* 最小高度 */
		minHeight: { type: Number, default: 320 },
		/* 只读 */
		readOnly: { type: Boolean, default: false },
		// 上传文件大小限制(MB)
		type: { type: String, default: 'url' },
		// 是否上传图片
		uploadImage: { type: Boolean, default: false },
		// 文本框提示文字
		placeholder: { type: String, default: '请输入内容' }
	},
	data() {
		let uploadTools = this.uploadImage ? ['image'] : undefined;
		let baseURL = !window.baseUrl ? process.env.VUE_APP_BASEURL : window.baseUrl;
		return {
			Quill: null,
			currentValue: '',
			uploadUrl: `${baseURL}tbSysAttachment/upload`,
			uploadParams: { showType: '1', type: '3' },
			options: {
				theme: 'snow',
				bounds: document.body,
				// debug: 'warn',
				modules: {
					imageDrop: true,
					imageResize: {
						displayStyles: {
							backgroundColor: 'black',
							border: 'none',
							color: 'white'
						},
						modules: ['Resize', 'DisplaySize', 'Toolbar']
					},
					// 工具栏配置
					toolbar: [
						['bold', 'italic', 'underline', 'strike'],
						['blockquote', 'header'], // 引用  代码块
						[{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
						[{ indent: '-1' }, { indent: '+1' }], // 缩进
						[{ size: ['small', false, 'large', 'huge'] }], // 字体大小
						[{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题 —— 下拉选择
						[{ color: [] }, { background: [] }],
						[{ align: [] }],
						['clean'], // 清除文本格式
						uploadTools
					]
 				},
				placeholder: this.placeholder,
				readOnly: this.readOnly
			}
		};
	},
	computed: {
		...mapGetters(['token', 'dictConst']),
		styles() {
			let style = {};
			if (this.minHeight) {
				style.minHeight = `${this.minHeight}px`;
			}
			if (this.height) {
				style.height = `${this.height}px`;
			}
			return style;
		},
		uploadSizes() {
			return Number(this.dictConst['SYS_FFCONFIG5_SIZE']);
		},
		suffixList() {
			return this.dictConst['SYS_FFCONFIG5_TYPE'].split(',');
		},
		uploadAccept() {
			return this.suffixList.map((n) => `.${n}`).join();
		},
		uploadHeader() {
			return { Authorization: this.token, userButton: 'a395e5424cad4effbd645407b1241213' };
		}
	},
	watch: {
		value: {
			handler(val) {
				if (val !== this.currentValue) {
					this.currentValue = val === null ? '' : val;
					if (this.Quill) {
						this.Quill.pasteHTML(this.currentValue);
					}
				}
			},
			immediate: true
		}
	},
	mounted() {
		this.init();
	},
	beforeDestroy() {
		this.Quill = null;
	},
	methods: {
		init() {
			const editor = this.$refs.editor;
			this.Quill = new Quill(editor, this.options);
			// 如果设置了上传地址则自定义图片上传事件
			if (this.type == 'url') {
				let toolbar = this.Quill.getModule('toolbar');
				toolbar.addHandler('image', (value) => {
					this.$refs['upload'].$el.querySelector('.uploadBtn').click();
				});
				toolbar.addHandler('video', (value) => {});
			}
			this.Quill.pasteHTML(this.currentValue);
			this.Quill.on('text-change', (delta, oldDelta, source) => {
				const html = this.$refs.editor.children[0].innerHTML;
				const text = this.Quill.getText();
				const quill = this.Quill;
				this.currentValue = html;
				this.$emit('input', html);
				this.$emit('on-change', { html, text, quill });
			});
			this.Quill.on('text-change', (delta, oldDelta, source) => {
				this.$emit('on-text-change', delta, oldDelta, source);
			});
			this.Quill.on('selection-change', (range, oldRange, source) => {
				this.$emit('on-selection-change', range, oldRange, source);
			});
			this.Quill.on('editor-change', (eventName, ...args) => {
				this.$emit('on-editor-change', eventName, ...args);
			});
		},

		handleBeforeUpload(file) {
			let fileArr = file.name.split('.');
			let suffix = fileArr[fileArr.length - 1];
			if (!this.suffixList.some((n) => n === suffix)) {
				this.$showCustomMessage('warning', '上传文件类型不正确');
				return false;
			} else if (this.uploadSizes * 1024 * 1024 < file.size) {
				this.$showCustomMessage('warning', '上传文件大于' + this.uploadSizes + 'MB');
				return false;
			}
		},

		handleUploadSuccess(res) {
			if (res.code === '0') {
				let length = this.Quill.getSelection().index;
				let datas = !!res.data && res.data.length > 0 && res.data[0] ? res.data[0] : {};
				this.Quill.focus();
				this.Quill.insertEmbed(length, 'image', datas.quoteAddr);
				this.Quill.setSelection(length + 1);
			}
		}
	}
};
</script>

<style>
.ql-editor {
	font-size: 16px;
	line-height: 1.5;
}
.editor,
.ql-toolbar {
	white-space: pre-wrap !important;
	line-height: normal !important;
}
.quill-img {
	display: none;
}
.ql-snow .ql-tooltip[data-mode='link']::before {
	content: '请输入链接地址:';
}
.ql-snow .ql-tooltip.ql-editing a.ql-action::after {
	border-right: 0px;
	content: '保存';
	padding-right: 0px;
}

.ql-snow .ql-tooltip[data-mode='video']::before {
	content: '请输入视频地址:';
}

.ql-snow .ql-picker.ql-size .ql-picker-label::before,
.ql-snow .ql-picker.ql-size .ql-picker-item::before {
	content: '14px';
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value='small']::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value='small']::before {
	content: '10px';
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value='large']::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value='large']::before {
	content: '18px';
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value='huge']::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value='huge']::before {
	content: '32px';
}

.ql-snow .ql-picker.ql-header .ql-picker-label::before,
.ql-snow .ql-picker.ql-header .ql-picker-item::before {
	content: '文本';
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value='1']::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value='1']::before {
	content: '标题1';
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value='2']::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value='2']::before {
	content: '标题2';
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value='3']::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value='3']::before {
	content: '标题3';
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value='4']::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value='4']::before {
	content: '标题4';
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value='5']::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value='5']::before {
	content: '标题5';
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value='6']::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value='6']::before {
	content: '标题6';
}

.ql-snow .ql-picker.ql-font .ql-picker-label::before,
.ql-snow .ql-picker.ql-font .ql-picker-item::before {
	content: '标准字体';
}
.ql-snow .ql-picker.ql-font .ql-picker-label[data-value='serif']::before,
.ql-snow .ql-picker.ql-font .ql-picker-item[data-value='serif']::before {
	content: '衬线字体';
}
.ql-snow .ql-picker.ql-font .ql-picker-label[data-value='monospace']::before,
.ql-snow .ql-picker.ql-font .ql-picker-item[data-value='monospace']::before {
	content: '等宽字体';
}

.ql-toolbar.ql-snow,
.ql-container.ql-snow {
	border-color: #dcdfe6;
}
</style>
<style lang="scss" scoped>
.quill_editor_wrapper::v-deep {
	.ql-toolbar {
		display: flex;
		flex-wrap: wrap;
	}
	.upload {
		display: none;
	}
}
</style>
